package com.ruoyi.common.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.InputStream;

public class QiNiuUtils {

    private static Configuration cfg;
    private static UploadManager uploadManager;
    private static String accessKey = "k7SWZ_AHnxoW3kXwARlUjNzoBi972uK_LkIJwdjD";
    private static String secretKey = "GxvAsEiX2hu1Pl05luXJdS0b0R2jXjImRZHzswaN";
    private static String bucket = "spongebob8080";

    static {

        cfg = Configuration.create(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        // 设置请求协议为http
        cfg.useHttpsDomains = false;
        uploadManager = new UploadManager(cfg);
    }

    /**
     * 上传
     * @param inputStream 文件内容
     * @param key 文件名
     */
    public static void upload(InputStream inputStream,String key){
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(inputStream,key,upToken,null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);
                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignored) {
                }
            }
        }
    }

}
